package com.gzwanchuang.lszg.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.allenliu.versionchecklib.v2.callback.CustomVersionDialogListener;
import com.gzwanchuang.lszg.R;
import com.gzwanchuang.lszg.base.MainApplication;
import com.gzwanchuang.lszg.dialog.BaseDialog;
import com.gzwanchuang.lszg.proto.Index;
import com.google.protobuf.InvalidProtocolBufferException;

/**
 * Created by AndroidIntexh1 on 2018/11/10.
 */

public class APKVersionCodeUtils {

    /**
     * 获取当前本地apk的版本
     *
     * @param mContext
     * @return
     */
    public static int getVersionCode(Context mContext) {
        int versionCode = 0;
        try {
            //获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = mContext.getPackageManager().
                    getPackageInfo(mContext.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 获取版本号名称
     *
     * @param context 上下文
     * @return
     */
    public static String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().
                    getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }

    public void checkVerison(byte[] response, Context mContext) {
        String versionName = APKVersionCodeUtils.getVerName(mContext);
        Index.get_app_version_info versionBean = null;
        try {
            versionBean = Index.get_app_version_info.parseFrom(response);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
        Log.e("mango", "checkVerison: " + versionBean);
        // 改为匹配版本号
        float serviceVersion = Float.valueOf(versionBean.getVersion());
        float locationeVersion = Float.valueOf(versionName);
        if (locationeVersion < serviceVersion) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                boolean hasInstallPermission = mContext.getPackageManager().canRequestPackageInstalls();
                if (!hasInstallPermission) {
                    androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(mContext);
                    builder.setTitle("提示");
                    builder.setMessage("请允许安装未知来源权限");
                    builder.setCancelable(false);
                    builder.setOnDismissListener(dialog -> {
                    });
                    builder.setNegativeButton("", (dialog, which) -> {

                    });
                    builder.setPositiveButton("设置", (dialog, which) -> {
                        startInstallPermissionSettingActivity(mContext);
                        ((Activity)mContext).finish();
                    });
                    builder.show();
                } else {
                    DownloadBuilder builder = AllenVersionChecker
                            .getInstance()
                            .downloadOnly(crateUIData(versionBean));
                    builder.setCustomVersionDialogListener(createCustomDialogOne());
                    if (versionBean.getForce().equals("1")) {
                        builder.setForceUpdateListener(MainApplication::finishAllActivity);
                    }
                    builder.setForceRedownload(true).executeMission(mContext);
                }
            } else {
                DownloadBuilder builder = AllenVersionChecker
                        .getInstance()
                        .downloadOnly(crateUIData(versionBean));
                builder.setCustomVersionDialogListener(createCustomDialogOne());
                if (versionBean.getForce().equals("1")) {
                    builder.setForceUpdateListener(MainApplication::finishAllActivity);
                }
                builder.setForceRedownload(true).executeMission(mContext);
            }
        }
    }


    private UIData crateUIData(Index.get_app_version_info versionBean) {
        UIData uiData = UIData.create();
        uiData.setTitle(versionBean.getTitle());
        uiData.setDownloadUrl(versionBean.getDownloadUrl());
        uiData.setContent(versionBean.getContext());
        uiData.getVersionBundle().putString("force", versionBean.getForce());
        return uiData;
    }


    /**
     * 务必用库传回来的context 实例化你的dialog
     * 自定义的dialog UI参数展示，使用versionBundle
     *
     * @return
     */
    private CustomVersionDialogListener createCustomDialogOne() {
        return (context, versionBundle) -> {
            BaseDialog baseDialog = new BaseDialog(context, R.style.BaseDialog, R.layout.custom_dialog_layout);
            TextView textView = baseDialog.findViewById(R.id.tv_msg);
            TextView title = baseDialog.findViewById(R.id.tv_title);
            ImageView canCle = baseDialog.findViewById(R.id.versionchecklib_version_dialog_cancel);
            if (versionBundle.getVersionBundle().getString("force").equals("1"))
                canCle.setVisibility(View.GONE);
            textView.setText(versionBundle.getContent());
            title.setText(versionBundle.getTitle());
            return baseDialog;
        };
    }


    private void startInstallPermissionSettingActivity(Context context) {
        Uri packageURI = Uri.parse("package:" + context.getPackageName());
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }


}
